import config from "../../config";
import {directionEnum} from "../enum/directionEnum";

export default abstract class modelAbstract {
  public abstract name: string
  abstract canvas: ICanvas
  abstract render(): void
  abstract image(): HTMLImageElement
  public direction:directionEnum = directionEnum.top
  public width = config.model.width
  public height = config.model.height

  constructor(
      public position: { x: number; y: number; }
  ) {
      this.randomDirection()
  }

  // 随机方向
  randomDirection() {
    const random = Math.random() - 0.45
    // 向下的概率大一点
    if (random < 0) {
      this.direction = Object.keys(directionEnum)[Math.floor(Math.random() * 4)] as directionEnum
    } else {
      this.direction = directionEnum.bottom
    }
  }

  // 绘制坦克
  protected draw() {
    this.canvas.ctx.drawImage(this.image(), this.position.x, this.position.y, config.model.width, config.model.height)
  }

  // 模型卸载
  public destroy() {
    this.canvas.removeModel(this)
    this.canvas.renderModels()
  }

  // 爆炸
  protected blast(model:IModel) {
    Array(...Array(8).keys()).reduce((promise, index) => {
      return new Promise(res => {
        setTimeout(() => {
          const img = new Image
          img.src = config.blast[index]
          img.onload = () => {
            this.canvas.ctx.drawImage(img, model.position.x, model.position.y, model.width, model.height)
            res(promise)
          }
        }, 100)
      })
    })
  }
}
